package com.xuelangyun.form.config;

import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.List;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Configuration;
import org.springframework.http.MediaType;
import org.springframework.http.converter.HttpMessageConverter;
import org.springframework.http.converter.json.MappingJackson2HttpMessageConverter;
import org.springframework.web.servlet.config.annotation.CorsRegistry;
import org.springframework.web.servlet.config.annotation.ResourceHandlerRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;

import com.fasterxml.jackson.databind.ObjectMapper;

/**
 * WebMvc配置
 *
 * @author weiqing.hk
 */
@Configuration
public class WebMvcConfig implements WebMvcConfigurer {

    @Autowired
    private ObjectMapper objectMapper;

    @Override
    public void configureMessageConverters(List<HttpMessageConverter<?>> converters) {

        List<MediaType> list = new ArrayList<MediaType>();
        list.add(MediaType.APPLICATION_JSON);

        //yyyy-MM-dd
        MappingJackson2HttpMessageConverter dateFormat2 = new MappingJackson2HttpMessageConverter();
        //设置日期格式
        //ObjectMapper objectMapper2 = new ObjectMapper();
        SimpleDateFormat smt2 = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        objectMapper.setDateFormat(smt2);
        dateFormat2.setObjectMapper(objectMapper);
        //设置中文编码格式

        dateFormat2.setSupportedMediaTypes(list);
        converters.add(dateFormat2);
    }

    @Override
    public void addResourceHandlers(ResourceHandlerRegistry registry) {
        registry.addResourceHandler("/static/**").addResourceLocations("classpath:/static/");
        registry.addResourceHandler("/**").addResourceLocations("classpath:/static/");
        registry.addResourceHandler("/swagger/**").addResourceLocations("classpath:/static/swagger/");
        // 解决swagger无法访问
        registry.addResourceHandler("/webjars/**").addResourceLocations("classpath:/META-INF/resources/webjars/");
        // 解决swagger的js文件无法访问
        registry.addResourceHandler("/swagger-ui.html").addResourceLocations("classpath:/META-INF/resources/");

    }

    @Override
    public void addCorsMappings(CorsRegistry registry) {
        registry.addMapping("/**").allowedMethods("*").allowedOriginPatterns("*").allowedHeaders("*").allowCredentials(true).maxAge(30 * 1000);
        // WebMvcConfigurer.super.addCorsMappings(registry);
    }

}
